﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Net.Mail;
using System.Net;
using Touch2Like.SharedLibrary;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace Touch2Like.Web
{
    public static class WebUtility
    {
        #region Get or set UserID value
        /// <summary>
        /// Get or set username value
        /// </summary>
        /// 
        public static string LogoOwner
        {
            get
            {
                try
                {
                    return HttpContext.Current.Session["LogoOwner"].ToString();
                }
                catch
                {
                    return "0";
                }
            }
            set
            {
                HttpContext.Current.Session["LogoOwner"] = value;
            }
        }

        public static string UserGUID
        {
            get
            {
                try
                {
                    return HttpContext.Current.Session["UserGUID"].ToString();
                }
                catch
                {
                    return "0";
                }
            }
            set
            {
                HttpContext.Current.Session["UserGUID"] = value;
            }
        }

        public static int TempUserID
        {
            get
            {
                try
                {
                    return Convert.ToInt32(HttpContext.Current.Session["TempUserID"].ToString());
                }
                catch
                {
                    return 0;
                }
            }
            set
            {
                HttpContext.Current.Session["TempUserID"] = value;
            }
        }
        #endregion

        #region Get or set username value
        /// <summary>
        /// Get or set username value
        /// </summary>
        public static string Username
        {
            get
            {
                try
                {
                    return HttpContext.Current.Session["Username"].ToString();
                }
                catch
                {
                    return "";
                }
            }
            set
            {
                HttpContext.Current.Session["Username"] = value;
            }
        }
        #endregion

        #region Get or set username value
        /// <summary>
        /// Get or set username value
        /// </summary>
        public static string AdminUsername
        {
            get
            {
                try
                {
                    return HttpContext.Current.Session["AdminUsername"].ToString();
                }
                catch
                {
                    return "";
                }
            }
            set
            {
                HttpContext.Current.Session["AdminUsername"] = value;
            }
        }
        #endregion

        public sealed class Authentication
        {
            private static void SendAuthenticationError(System.Web.UI.Page page)
            {
                page.Page.Response.StatusCode = 401;
                String Result = @"
            <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"">
            <HTML>
              <HEAD>
                <TITLE>Error</TITLE>
                <META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; charset=ISO-8859-1"">
              </HEAD>
              <BODY><H1>401 Unauthorized.</H1></BODY>
            </HTML>
        "; // html does not care about the tabulation above
                page.Page.Response.Write(Result);
                page.Page.Response.Flush();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }

            // Probably not the best unit for this, but avoiding excessive .cs files.  My current use of this is a form of authentication failure, as the xml provided was ill-formed.
            public static void SendError(System.Web.UI.Page page, int statusCode, string message)
            {
                page.Page.Response.StatusCode = 401;
                String Result = @"
            <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd"">
            <HTML>
              <HEAD>
                <TITLE>Error</TITLE>
                <META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; charset=ISO-8859-1"">
              </HEAD>
              <BODY><H1>" + statusCode.ToString() + " " + page.Server.HtmlEncode(message) + @".</H1></BODY>
            </HTML>
        "; // html does not care about the tabulation above
                page.Page.Response.Write(Result);
                page.Page.Response.Flush();
                HttpContext.Current.ApplicationInstance.CompleteRequest();

            }

            public static bool CheckBasicAuthentication(System.Web.UI.Page page, string expectedUserName, string expectedUserPassword)
            {
                // Check authentication
                String authenticationHeader = "";
                object authenticationObject = page.Page.Request.Headers["Authorization"];
                if (authenticationObject == null)
                {
                    SendAuthenticationError(page);
                    return false;
                }

                authenticationHeader = authenticationObject.ToString();

                if (authenticationHeader.ToLower().IndexOf("basic") < 0 || authenticationHeader.Length < 7)
                {
                    SendAuthenticationError(page);
                    return false;
                }

                authenticationHeader = authenticationHeader.Substring(5); // basic + 5 (index == 0)

                byte[] AuthenticationBinary = Convert.FromBase64String(authenticationHeader);
                authenticationHeader = System.Text.Encoding.UTF8.GetString(AuthenticationBinary);

                if (authenticationHeader.IndexOf(":") < 0)
                {
                    SendAuthenticationError(page);
                    return false;
                }


                //Don't use split on :, since it could be part of the password.  Only the first matters.  It cannot be part of the user name.
                string IncomingUserName = authenticationHeader.Substring(0, authenticationHeader.IndexOf(":"));
                authenticationHeader = authenticationHeader.Replace(IncomingUserName + ":", "");
                string IncomingUserPassword = authenticationHeader;

                if (IncomingUserName != expectedUserName || IncomingUserPassword != expectedUserPassword)
                {
                    SendAuthenticationError(page);
                    return false;
                }

                return true;
            }
        }

        public static string GetMD5String(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] b = Encoding.UTF8.GetBytes(str);
            byte[] md5b = md5.ComputeHash(b);
            md5.Clear();
            StringBuilder sb = new StringBuilder();
            foreach (var item in md5b)
            {
                sb.Append(item.ToString("x2"));
            }
            return sb.ToString();
        }

        public static void SendEmail(string email, string username, int type)
        {
            MailAddress from = new MailAddress(GlobalManager.EmailAccount.FromEmail, "CAMINTEL Group Membership");
            MailAddress to = new MailAddress(email, username);
            MailMessage message = new MailMessage(from, to);
            if (type == 0)
            {
                message.Subject = "Please confirm your emaill address to finish creating the online profile at CAMINTEL Group";
                string content = "<p style='margin:0px;padding:0px;'><strong style='font-size:16px;line-height:32px;color:#333333;font-family:arial,sans-serif;'>CAMINTEL Group</strong></p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>&nbsp;</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Dear " + username + ", welcome!</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>&nbsp;</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Thank you for registering on CAMINTEL Group website, click the link below to active your account.</p>";
                //content += "<p style='margin:0px;padding:0px;'><a href='http://www.camintelgroup.com/Customer/active.aspx?u=" + username + "&t=" + UrlEncode(Utility.Encryption.Encrypt(username)) + "' style='line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc' target='_blank'>http://www.camintelgroup.com/Customer/active.aspx?u=" + username + "&t=" + Server.UrlEncode(Utility.Encryption.Encrypt(username)) + "</a></p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#979797;font-family:arial,sans-serif;'>(If the above link does not work, copy and paste the address into your web browser.)</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>&nbsp;</p>";
                content += "<div style='line-height:80px;height:80px;'></div><p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>The CAMINTEL Group</p>";
                content += "<p style='margin:0px;padding:0px;'><a href='http://www.camintelgroup.com' style='line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc' target='_blank'>http://www.camintelgroup.com</a></p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>&nbsp;</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:9px;color:#333333;font-family:arial,sans-serif;'>© 2012, CAMINTEL Group, LLC</p>";

                message.Body = content;
            }
            else if (type == 1)
            {
                message.Subject = "forget password of CAMINTEL";
                string content = "<p style='margin:0px;padding:0px;'><strong style='font-size:14px;line-height:24px;color:#333333;font-family:arial,sans-serif;'>Dear " + username + "</strong></p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Welcome!</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>You had register a acount on our site, click the link below to change your password.</p>";
                content += "<p style='margin:0px;padding:0px;'><a href='http://www.camintelgroup.com//Customer/changepassword.aspx?u=" + username + "&t=" + Utility.Encryption.Encrypt(username) + "' style='line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc' target='_blank'>http://www.camintelgroup.com/Customer/changepassword.aspx?u=" + username + "&t=" + Utility.Encryption.Encrypt(username) + "</a></p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#979797;font-family:arial,sans-serif;'>(If you can't open it, copy it and paste to your browser to visit the url.)</p>";
                content += "<div style='line-height:80px;height:80px;'></div><p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>CAMINTEL</p>";
                content += "<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>" + DateTime.Now.ToString("yyyy-MM-dd HH：mm：ss：ffff") + "</p>";

                message.Body = content;
            }
            message.IsBodyHtml = true;
            string host = GlobalManager.EmailAccount.Host;
            SmtpClient client = new SmtpClient(host, 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential("member@camintelgroup.com", "HotTuna4698!");
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            client.Send(message);

        }

        public static void SendContactUsEmail(string FullName, string CompanyName, string TelephoneNumber, string EmailAddress, string Message)
        {
            MailAddress from = new MailAddress(GlobalManager.EmailAccount.FromEmail, "CAMINTEL Contact Form");
            MailAddress to = new MailAddress("info@camintelgroup.com", "CAMINTEL");
            MailMessage message = new MailMessage(from, to);

            message.Subject = "Mon-Tag-U, you got an email from a follower";
            StringBuilder sb = new StringBuilder();
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Mon-Tag-U, here is the information from the follower<br/><br/></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Name: <b>" + FullName.ToString() + "</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Company Name: <b>" + CompanyName + "</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Telephone Number: <b>" + TelephoneNumber + "</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Email Address: <b>" + EmailAddress + "</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Message: <b>" + Message.ToString() + "</b><br/><br/></p>");
            sb.Append("<div style='line-height:50px;height:50px;'></div><p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>The CAMINTEL Group</p>");
            sb.Append("<p style='margin:0px;padding:0px;'><a href='http://www.camintelgroup.com' style='line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc' target='_blank'>http://www.camintelgroup.com</a></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:9px;color:#333333;font-family:arial,sans-serif;'>© 2013, CAMINTEL Group, LLC</p>");

            message.Body = sb.ToString();

            message.IsBodyHtml = true;
            string host = GlobalManager.EmailAccount.Host;
            SmtpClient client = new SmtpClient(host, 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential("member@camintelgroup.com", "HotTuna4698!");
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            client.Send(message);

        }

        public static void SendCouponCodeEmail(string CouponCode, string EmailAddress, string CouponValue)
        {
            MailAddress from = new MailAddress("member@camintelgroup.com", "CAMINTEL Coupon");
            MailAddress to = new MailAddress(EmailAddress, "Customer");
            MailMessage message = new MailMessage(from, to);

            message.Subject = "Thank you! Here is the coupon.";
            StringBuilder sb = new StringBuilder();
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>&nbsp;</p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Dear Customer, thank you for providing the feedback to us, it meant a lot.  Here is the coupon code for next time you dine in with us.</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Coupon Value: <b>" + CouponValue + "%</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Coupon Code: <b>" + CouponCode + "</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'><img src='https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=" + HttpUtility.UrlEncode("http://www.camintelgroup.com/Touch2Rate/Redeem.aspx?couponcode=" + CouponCode) + "' /></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'><p>&nbsp;</p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Again, thanks for dining with us and we hope to see you next time!</b></p>");
            sb.Append("<div style='line-height:50px;height:50px;'></div><p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>The CAMINTEL Group</p>");
            sb.Append("<p style='margin:0px;padding:0px;'><a href='http://www.camintelgroup.com' style='line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc' target='_blank'>http://www.camintelgroup.com</a></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:9px;color:#333333;font-family:arial,sans-serif;'>© 2013, CAMINTEL Group, LLC</p>");

            message.Body = sb.ToString();

            message.IsBodyHtml = true;
            string host = "173.194.64.108";
            SmtpClient client = new SmtpClient(host, 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential("member@camintelgroup.com", "HotTuna4698!");
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            client.Send(message);

        }

        public static void SendReviewThankYouEmail(string EmailAddress)
        {
            MailAddress from = new MailAddress(GlobalManager.EmailAccount.FromEmail, "CAMINTEL Coupon");
            MailAddress to = new MailAddress(EmailAddress, "Customer");
            MailMessage message = new MailMessage(from, to);

            message.Subject = "Thank you! ";
            StringBuilder sb = new StringBuilder();
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>&nbsp;</p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Dear Friend, thank you for providing the feedback to us, we will improve our system to serve you better.</b></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'><p>&nbsp;</p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>Best,</b></p>");
            sb.Append("<div style='line-height:50px;height:50px;'></div><p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'>The CAMINTEL Group</p>");
            sb.Append("<p style='margin:0px;padding:0px;'><a href='http://www.camintelgroup.com' style='line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc' target='_blank'>http://www.camintelgroup.com</a></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:arial,sans-serif;'></p>");
            sb.Append("<p style='margin:0px;padding:0px;line-height:24px;font-size:9px;color:#333333;font-family:arial,sans-serif;'>© 2013, CAMINTEL Group, LLC</p>");

            message.Body = sb.ToString();

            message.IsBodyHtml = true;
            string host = GlobalManager.EmailAccount.Host;
            SmtpClient client = new SmtpClient(host, 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential("member@camintelgroup.com", "HotTuna4698!");
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            client.Send(message);

        }
    }
}